//
//  WHContactsEditController.m
//  AddressBook
//
//  Created by  on 2020/7/28.
//  Copyright © 2020 wh. All rights reserved.
//

#import "WHContactsEditController.h"
#import "WHContactsEditTableView.h"
#import "MacroDefinition.h"
#import "WHSingleton.h"
#import "DBHelper.h"
#import "WHAlertTool.h"
#import "UIImageTool.h"
#import "WHHeaderView.h"



@interface WHContactsEditController () <WHHeaderImageDelegate,WHContactsEditTableViewDelegate,
UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@property (nonatomic, strong) WHContactsEditTableView *editTableView;
@property (nonatomic, strong) WHHeaderView *headerView;
@property (nonatomic, strong) UIButton *deleteButton;

@property (nonatomic, assign) CGFloat headerViewHeight;


@end

@implementation WHContactsEditController
{
    NSString *_name;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [super setRightBarButtonItemTitle:@"保存"];
    [super setLefttBarButtonItemTitle:@"返回"];
    self.headerViewHeight = kMAXHEIGHT;
    [self initWithView];
}

#pragma mark - 添加视图
- (void)initWithView
{
    [self.view addSubview:self.editTableView];
    [self.view addSubview:self.headerView];
    [self.view addSubview:self.deleteButton];
}

- (void)viewWillAppear:(BOOL)animated
{
    if (_name) {
        self.deleteButton.hidden = NO;
    }else{
        self.deleteButton.hidden = YES;
    }
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
    
}

- (void)viewWillDisappear:(BOOL)animated{
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:nil];
}

//打开相册
-(void)openPhotoLibrary{
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]){
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];
        imagePicker.allowsEditing = YES;
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        imagePicker.delegate = self;
        [self presentViewController:imagePicker animated:YES completion:^{
            NSLog(@"打开相册");
        }];
    }else{
        NSLog(@"不能打开相册");
    }
}
//选择图片
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info {
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    NSString *imageStr = [UIImageTool UIImageToBase64Str:image];
    [self.headerView setDataWithImageStr:imageStr];
    [WHSingleton setDataWithIndex:100 content:imageStr];
    [self dismissViewControllerAnimated:NO completion:nil];
    
}
//按照名字 搜索数据
- (void)searchDataWithName:(NSString *)name
{
    _name = name;
    __weak typeof(self) weakself = self;
    [DBHelper searchWithName:_name
                successBlock:^(NSMutableArray * _Nonnull arr) {
        [weakself.editTableView setContentWithArr:arr];
        [weakself.headerView setDataWithImageStr:arr[3]?arr[3]:@""];
    } failureBlock:^(NSString * _Nonnull str) {
        NSLog(@"%@",str);
    }];
}

- (void)leftButtonAction{
    [self.navigationController popViewControllerAnimated:NO];
}

//保存按钮事件
- (void)rightButtonAction
{
    __weak typeof(self) weakSelf = self;
    [self.view endEditing:YES];
    if ([[WHSingleton shareInstance].name isEqualToString:@""] ||
        [[WHSingleton shareInstance].phone isEqualToString:@""] ||
        [[WHSingleton shareInstance].address isEqualToString:@""] ||
        [[WHSingleton shareInstance].imageStr isEqualToString:@""]) {
        [WHAlertTool presentAlertWith:@"请将信息补充完整" controller:weakSelf actionblock:^{
            NSLog(@"请将信息补充完整");
        }];
    }else{
        if (!_name) {
            //新建联系人
            [DBHelper insertDataWithName:[WHSingleton shareInstance].name
                                   phone:[WHSingleton shareInstance].phone
                                 address:[WHSingleton shareInstance].address
                                   image:[WHSingleton shareInstance].imageStr
                            successBlock:^{
                [WHAlertTool presentAlertWith:@"保存成功" controller:weakSelf actionblock:^{
                    [weakSelf.navigationController popToRootViewControllerAnimated:YES];
                    [WHSingleton deleteAll];
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"notifi" object:nil];
                }];
            }failureBlock:^(NSString * _Nonnull str) {
                [WHAlertTool presentAlertWith:@"保存失败，换个名字试试" controller:weakSelf actionblock:^{
                    NSLog(@"保存失败");
                }];
            }];
            
        }else{
            // 修改联系人 先删除后添加
            [DBHelper deleteWithName:_name successBlock:^{
                [DBHelper insertDataWithName:[WHSingleton shareInstance].name
                                       phone:[WHSingleton shareInstance].phone
                                     address:[WHSingleton shareInstance].address
                                       image:[WHSingleton shareInstance].imageStr
                                successBlock:^{
                    [WHAlertTool presentAlertWith:@"保存成功" controller:weakSelf actionblock:^{
                        [weakSelf.navigationController popToRootViewControllerAnimated:YES];
                        [WHSingleton deleteAll];
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"notifi" object:nil];
                    }];
                }failureBlock:^(NSString * _Nonnull str) {
                    [WHAlertTool presentAlertWith:@"保存失败" controller:weakSelf actionblock:^{
                        NSLog(@"保存失败");
                    }];
                }];
            }failureBlock:^(NSString * _Nonnull str) {
                NSLog(@"这里是先删除在存储出了问题");
            }];
            
        }
    }
}
//删除按钮事件
- (void)deleteClickACtion
{
    __weak typeof(self) weakSelf = self;
    [DBHelper deleteWithName:_name
                successBlock:^{
        [WHAlertTool presentAlertWith:@"删除成功" controller:weakSelf actionblock:^{
            [weakSelf.navigationController popToRootViewControllerAnimated:YES];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"notifi" object:nil];
        }];
    } failureBlock:^(NSString * _Nonnull str) {
        NSLog(@"%@",str);
    }];
}
//点击图片事件
- (void)imageAction
{
    [self openPhotoLibrary];
}
#pragma mark - WHTableViewHeaderDelegate
- (void)editTableGetScrollContentOffsetY:(CGFloat)offsetY
{
    if (offsetY > 0) {
        if (self.headerViewHeight > KMINHEIGHT) {
            self.headerViewHeight -= offsetY;
        }
    }
    if (offsetY < 0) {
        if (self.headerViewHeight < kMAXHEIGHT) {
            self.headerViewHeight -= offsetY;
        }
    }
    [self setViewFrame];
}
- (void)editTableStopScrollAction
{
    if (self.headerViewHeight > KMIDDLEHEIGHT) {
        self.headerViewHeight = kMAXHEIGHT;
    }else if (self.headerViewHeight < KMIDDLEHEIGHT){
        self.headerViewHeight = KMINHEIGHT;
    }
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:0.1 animations:^{
        [weakSelf setViewFrame];
    }];
}


- (void)setViewFrame
{
    self.headerView.frame = CGRectMake(0, 0, ScreenWidth, self.headerViewHeight);
    self.editTableView.frame = CGRectMake(0, self.headerViewHeight, ScreenWidth, ScreenHeight-self.headerViewHeight);
}
#pragma mark - 懒加载
- (WHContactsEditTableView *)editTableView
{
    if (!_editTableView) {
        _editTableView = [[WHContactsEditTableView alloc] initWithFrame:CGRectMake(0, self.headerViewHeight, ScreenWidth, ScreenHeight-self.headerViewHeight)
                                                                  style:UITableViewStylePlain];
        _editTableView.editTableViewDelegate = self;
    }
    return _editTableView;
}
- (WHHeaderView *)headerView
{
    if (!_headerView) {
        _headerView = [[WHHeaderView alloc] init];
        _headerView.frame = CGRectMake(0, 0, ScreenWidth, self.headerViewHeight);
        _headerView.headerDelegate = self;
    }
    return _headerView;
}

- (UIButton *)deleteButton
{
    if (!_deleteButton) {
        _deleteButton = [[UIButton alloc] init];
        _deleteButton.frame = CGRectMake((ScreenWidth-150)/2, ScreenHeight - 200, 150, 40);
        _deleteButton.backgroundColor = UIColor.redColor;
        _deleteButton.layer.cornerRadius = 20;
        _deleteButton.hidden = NO;
        _deleteButton.titleLabel.font = [UIFont systemFontOfSize:22];
        [_deleteButton setTitle:@"删除" forState:UIControlStateNormal];
        [_deleteButton setTintColor:UIColor.whiteColor];
        [_deleteButton addTarget:self action:@selector(deleteClickACtion) forControlEvents:UIControlEventTouchUpInside];
    }
    return _deleteButton;
}
@end
